<template>
  <div ref="chartRef" style="width: 100%; height: 100%" />
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch, nextTick, defineEmits } from "vue";
import * as echarts from "echarts";
const emit = defineEmits(["clickChart"]);
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  type: {
    type: String,
    default: "pie"
  },
  extraOptions: {
    type: Object,
    default: () => ({})
  }
});

const chartRef = ref(null);
let myChart = null;
const getChartConfig = async () => {
  try {
    const configModule = await import(`./options/${props.type}.ts`);
    return configModule.default;
  } catch (error) {
    console.error("Error fetching chart config:", error);
    return {};
  }
};
// 定义点击事件处理函数
const handleChartClick = params => {
  emit("clickChart", params);
  // 可以在这里添加更多逻辑
};
const initChart = async () => {
  const configFunc = await getChartConfig();
  if (!myChart) {
    myChart = echarts.init(chartRef.value);
  }
  const defaultOptions = configFunc(props.data);
  const option = {
    ...defaultOptions,
    ...props.extraOptions
  };
  // const option = {
  //   ...defaultOptions,
  //   ...config,
  //   series: [
  //     {
  //       ...defaultOptions.series[0],
  //       ...((config.series && config.series[0]) || {})
  //     }
  //   ]
  // };
  console.log(option, "option");
  myChart.clear();
  myChart.setOption(option, true);
  myChart.on("click", handleChartClick);
};

const resizeChart = () => {
  if (myChart) {
    myChart.resize();
  }
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", resizeChart);
});

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
  window.removeEventListener("resize", resizeChart);
});

watch(
  [() => props.data, () => props.type, () => props.extraOptions],
  () => {
    if (chartRef.value) {
      initChart();
    }
  },
  {
    deep: true
  }
);
</script>
